import json

from django.http import HttpResponse, JsonResponse
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.views import APIView
from django.shortcuts import render
import logging
from app.tools import md5

from app import models
from serializers import MySerializer1, MySerializer

logger = logging.getLogger('log')
# Create your views here.

def testLog(request):
    logger.info("success")
    logger.error("failed")
    return HttpResponse(0)

def userLogin(request):
    if request.method == 'POST':
        ret = {
            "code":1000,
            "msg":None
        }
        try:
            data = json.loads(request.body)
            username = data['username']
            password = data['password']
            data = models.UserInfo.objects.filter(
                username=username,
                password=password,
            )
            print(data)
            if len(data) !=1:
                raise Exception
            else:
                ret['usertoken'] = data[0].token
                logger.info("用户:"+username+"成功登录")
        except Exception as e:
            logger.error(e)
            ret['code'] = 2000
            ret['msg'] = "用户名或密码错误"
        return JsonResponse(ret)

# def userReg(request):
#     if request.method == 'POST':
#         ret = {
#             "code":1000,
#             "msg":None
#         }
#         try:
#             data = json.loads(request.body)
#             username = data['username']
#             password = data['password']
#             token = md5(username)
#             models.UserInfo.objects.create(
#                 username=username,
#                 password=password,
#                 token=token
#             )
#         except Exception as e:
#             logger.error(e)
#             ret['code'] = 2000
#             ret['msg'] = e
#         return JsonResponse(ret)

class UserReg(viewsets.ModelViewSet):
    """
         list:
         返回所有项目信息

         create:
         添加一条数据
    """
    queryset = models.UserInfo.objects.all()
    serializer_class = MySerializer